<template>
  <basic-container>
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <!-- 微信公众号 -->
      <el-tab-pane v-for="(item, index) in optionList" :key="index" :name="formList[index].type" :label="formList[index].type">
        <avue-form :option="item" v-model="formList[index]">
          <template slot-scope="scope" slot="menuForm">
            <el-button icon="el-icon-check"
                        size="small"
                        v-if="isEdit"
                        @click="save(index)"
                        >保存</el-button>
            <el-button type="primary"
                        icon="el-icon-edit"
                        size="small"
                        v-if="!isEdit"
                        @click="clickEdit(index)"
                        >编辑</el-button>
          </template>
        </avue-form>
      </el-tab-pane>
    </el-tabs>
  </basic-container>
</template>

<script>
import {exportSysThirdPartyInfoExcel,saveOrUpdateSysThirdPartyInfo,saveOrUpdateSysThirdPartyInfoList,saveSysThirdPartyInfo,saveSysThirdPartyInfoList,deleteSysThirdPartyInfo,querySysThirdPartyInfo,querySysThirdPartyInfoListPage,updateSysThirdPartyInfo,deleteSysThirdPartyInfoList} from '@/api/system/sysThirdPartyInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
export default {
  components: {
    // updateHistory
  },
  data() {
    return {
      // 编辑状态控制
      isEdit: false,
      activeName: '微信公众号',
      currentType: '微信公众号',
      // 公共字段
      commonForm: {
        id: '',
        tenantId: '',
        type: '',
        dataSign: '',
        validFlag: '',
        createUserName: '',
        createRealName: '',
        createDatetime: '',
        updateUserName: '',
        updateRealName: '',
        updateDatetime: '',
        reserveDecimal1: 0,
        reserveDecimal2: 0,
        reserveString1: '',
        reserveString2: ''
      },
      // form列表
      formList: [
        // 微信公众号
        {
          id: '',
          tenantId: '',
          type: '微信公众号'
        },
        // 站内消息
        {
          id: '',
          tenantId: '',
          type: '站内消息'
        },
        // 腾讯会议
        {
          id: '',
          tenantId: '',
          type: '腾讯会议'
        },
        // 腾讯短信
        {
          id: '',
          tenantId: '',
          type: '腾讯短信'
        },
        // APP个推
        {
          id: '',
          tenantId: '',
          type: 'APP个推 '
        },
        // 邮件
        {
          id: '',
          tenantId: '',
          type: '邮件'
        },
        // 金山WPS
        {
          id: '',
          tenantId: '',
          type: '金山WPS'
        },
        // 钉钉消息
        {
          id: '',
          tenantId: '',
          type: '钉钉消息'
        },
      ],
      optionList: [
        // 微信公众号
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: 'App ID',
              prop: 'appId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App Secret',
              prop: 'appSecret', 
              type: 'input',
              disabled: true
            },
            {
              label: 'Token',
              prop: 'token', 
              type: 'input',
              disabled: true
            },
            {
              label: '获取token地址',
              prop: 'accessTokenUrl', 
              type: 'input',
              disabled: true
            },
            {
              label: '获取用户信息地址',
              prop: 'userInfoUrl', 
              type: 'input',
              disabled: true
            },
            {
              label: '发送模板消息地址',
              prop: 'sendTemplateMsgUrl', 
              type: 'input',
              disabled: true
            },
            {
              label: '关注提示语',
              prop: 'notice', 
              type: 'textarea',
              span:24,
              disabled: true
            },
            {
              label: '微信发送开关',
              prop: 'wechatSendChecked', 
              type: 'switch',
              disabled: true
            }
          ]
        },
        // 站内消息
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: '发送地址',
              prop: 'sendAddress', 
              type: 'input',
              span: 12,
              disabled: true
            },
            {
              label: '发送端口',
              prop: 'port', 
              type: 'input',
              span: 12,
              disabled: true
            },
            {
              label: '终端类型',
              prop: 'terminalType', 
              type: 'select',
              span: 12,
              disabled: true,
              dicData: [
                {
                  label: '全部',
                  value: 'all'
                },
                {
                  label: 'PC端',
                  value: 'pc'
                },
                {
                  label: '移动端',
                  value: 'app'
                }
              ]
            },
            {
              label: '站内消息开关',
              prop: 'noticeMsgChecked', 
              type: 'switch',
              span: 12,
              disabled: true
            }
          ]
        },
        // 腾讯会议
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: 'Secret ID',
              prop: 'secretId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'Secret Key',
              prop: 'secretKey', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App ID',
              prop: 'appId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'SDK ID',
              prop: 'sdkId', 
              type: 'input',
              disabled: true
            },
            {
              label: '创建会议url',
              prop: 'createMeetingUrl', 
              type: 'input',
              disabled: true
            },
            {
              label: '创建会议uri',
              prop: 'createMeetingUri', 
              type: 'input',
              disabled: true
            },
            {
              label: '腾讯会议开关',
              prop: 'tencentMeetingChecked', 
              type: 'switch',
              disabled: true
            }
          ]
        },
        // 腾讯短信
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: 'App ID',
              prop: 'appId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App Key',
              prop: 'appKey', 
              type: 'input',
              disabled: true
            },
            {
              label: '短信签名',
              prop: 'smsSign', 
              type: 'input',
              disabled: true
            },
            {
              label: '短信开关',
              prop: 'smsChecked', 
              type: 'switch',
              disabled: true
            }
          ]
        },
        // APP个推
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: 'App ID',
              prop: 'appId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App Key',
              prop: 'appKey', 
              type: 'input',
              disabled: true
            },
            {
              label: 'Master Secret',
              prop: 'masterSecret', 
              type: 'input',
              disabled: true
            },
            {
              label: '推送开关',
              prop: 'pushChecked', 
              type: 'switch',
              disabled: true
            }
          ]
        },
        // 邮件
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: '邮件服务器地址',
              prop: 'host', 
              type: 'input',
              disabled: true
            },
            {
              label: '端口',
              prop: 'port', 
              type: 'input',
              disabled: true
            },
            {
              label: '认证用户名',
              prop: 'userName', 
              type: 'input',
              disabled: true
            },
            {
              label: '认证密码',
              prop: 'password', 
              type: 'input',
              disabled: true
            },
            {
              label: '加密协议',
              prop: 'enc', 
              type: 'input',
              disabled: true
            },
            {
              label: '发送者邮箱地址',
              prop: 'fromEmail', 
              type: 'input',
              disabled: true
            },
            {
              label: '发送者邮箱签名',
              prop: 'fromNickName', 
              type: 'input',
              disabled: true
            },
            {
              label: '邮件发送开关',
              prop: 'emailSendChecked', 
              type: 'switch',
              disabled: true
            }
          ]
        },
        // 金山WPS
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: 'App ID',
              prop: 'appId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App Secret',
              prop: 'appsecret', 
              type: 'input',
              disabled: true
            },
            {
              label: 'WPS 地址',
              prop: 'wpsDomain', 
              type: 'input',
              disabled: true
            },
            {
              label: '文档服务地址',
              prop: 'fileDomin', 
              type: 'input',
              disabled: true
            }
          ]
        },
        // 钉钉消息
        {
          labelWidth: 150,
          submitBtn: false,
          emptyBtn: false,
          column:[
            {
              label: 'Corp Id',
              prop: 'corpId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'Agent Id',
              prop: 'agentId', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App Key',
              prop: 'appKey', 
              type: 'input',
              disabled: true
            },
            {
              label: 'App Secret',
              prop: 'appSecret', 
              type: 'input',
              disabled: true
            },
            {
              label: 'Token过期时间',
              prop: 'tokenExpired', 
              type: 'input',
              disabled: true
            },
            {
              label: '消息开关',
              prop: 'dingtalkChecked', 
              type: 'switch',
              disabled: true
            }
          ]
        },
      ],
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','orgTree','userInfo','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.sys_third_party_info_add, false),
        viewBtn: this.vaildData(this.permission.sys_third_party_info_view, false),
        delBtn: this.vaildData(this.permission.sys_third_party_info_delete, false),
        editBtn: this.vaildData(this.permission.sys_third_party_info_edit, false),
        printBtn: this.vaildData(this.permission.sys_third_party_info_print, false),
        searchBtn:this.vaildData(this.permission.sys_third_party_info_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    }
  },
  methods: {
    /**
     * 切换页签
     */
    handleClick(tab, event){
      this.$console.log('====tab==',tab, event);
      this.currentType = tab.name;
      this.onLoad();
    },

    /**
     * 点击编辑按钮
     */
    clickEdit(index){
      this.dealColumn(index, false);
      this.isEdit = true;
    },
    
    /**
     * 处理字段可编辑状态
     */
    dealColumn(index, state){
      let option = this.optionList[index];
      for(let i in option.column){
        //this.$console.log('i===>', i)
        option.column[i].disabled = state;
      }
    },

    /**
     * 保存配置
     */
    save(index){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      // this.$message.success(JSON.stringify(this.wxForm))
      //this.$console.log('this.formList====>', this.formList);
      let form = {};
      this.formList.map(item =>{
        if(item.type === this.currentType){
          form = item;
        }
      });

      if(form.id){ // 修改
        // 公共字段
        let singleBody = this.deepClone(this.commonForm);

        let param = this.deepClone(form);
        delete param.id;
        delete param.tenantId;
        delete param.type;
        singleBody.thirdPartyConfigContent = JSON.stringify(param);

        let reqParams = {
          singleBody: singleBody
        };
        let commonData = reqCommonMsg(reqParams)
        updateSysThirdPartyInfo(commonData).then(() => {
          this.singleBody={};
          this.isEdit = false;
          this.dealColumn(index, true);
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });  
      }else{ // 新增
        let singleBody = {
          type: this.currentType,
          thirdPartyConfigContent: JSON.stringify(form)
        }
        let reqParams = {
          singleBody: singleBody
        };
        let commonData = reqCommonMsg(reqParams)
        saveSysThirdPartyInfo(commonData).then(() => {
          this.singleBody={};
          this.isEdit = false;
          this.dealColumn(index, true);
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });     
      }
    },

    saveWx(){

    },

    /**
     * 加载数据
     */
    onLoad() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      let reqParams =  {
        singleBody: {
          type: this.currentType
        }
      }
      let commonData = reqCommonMsg(reqParams)
      querySysThirdPartyInfoListPage(commonData).then(res => {
        const listBody = res.data.body.listBody;
        if(listBody && listBody.length > 0){
          let result = listBody[0];
          for(let i in this.formList){
            if(this.formList[i].type === result.type){
              // 公共字段赋值
              let commonData = this.deepClone(result);
              delete commonData.thirdPartyConfigContent;
              this.commonForm = commonData;

              // thirdPartyConfigContent 字段处理为json
              if(result.thirdPartyConfigContent){
                this.formList[i] = JSON.parse(result.thirdPartyConfigContent);
              }
              this.formList[i].id = result.id;
              this.formList[i].tenantId = result.tenantId;
              this.formList[i].type = result.type;
              //this.$console.log('====>this.commonForm>>>>', this.commonForm);
              //this.$console.log('====>item>>>>', item);
              //this.$console.log('====>this.formList>>>>', this.formList);
              break;
            }
          }
          this.$forceUpdate();
          
        }
        loading.close();
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysThirdPartyInfo(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        done();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysThirdPartyInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        done();
      });
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysThirdPartyInfo(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.sys_third_party_info_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    /**
     * 批量导入
     */
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              id:field[0].trim(),
              tenantId:field[1].trim(),
              type:field[2].trim(),
              secretId:field[3].trim(),
              secretKey:field[4].trim(),
              appSecretId:field[5].trim(),
              appSecretKey:field[6].trim(),
              sdkId:field[7].trim(),
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysThirdPartyInfoList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysThirdPartyInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.reqParams =  {
          singleBody: {
            id:this.form.id
          }
        }
        let commonData = reqCommonMsg(this.reqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        querySysThirdPartyInfo(commonData).then(res => {
          this.form = res.data.body.singleBody;
          loading.close();
          done();
        }, error => {
          //this.$console.log(error);
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
     	done();
      }
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportSysThirdPartyInfoExcel(this.commonData);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["bizType"]');
      this.findObject(this.option.column, 'bizType').dicData = dicData.bizType;
    }
  },
  created() {
    // 加载第一个页签的数据
    this.onLoad();
    this.showColumn = this.$getStore({name: this.userInfo.userId+'sysThirdPartyInfoColumn'});
    //获取业务字典
    // setTimeout(() => {
    //  this.getBizDict();
    // }, 1000);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'sysThirdPartyInfoColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name:  this.userInfo.userId+'sysThirdPartyInfoColumn', content: this.showColumn});
    }
  }
};
</script>
